//
//  GSRegisterViewController.m
//  GameSky
//
//  Created by lanou on 16/1/19.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSRegisterViewController.h"
#import "GSRegisterView.h"

@interface GSRegisterViewController ()

@property (nonatomic, strong) GSRegisterView *registerView;

@end

@implementation GSRegisterViewController
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:155/255.0 green:37/255.0 blue:34/255.0 alpha:1.0];
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [self.view endEditing:YES];
    self.navigationController.navigationBar.hidden = YES;
}
#pragma mark--------------视图加载完成--------------------
- (void)viewDidLoad {
    [super viewDidLoad];
    // 夜间模式
    self.view.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    self.navigationItem.title = @"注册用户";
// 添加子视图
    [self addSubviews];
}

#pragma mark------------添加子视图-----------------------
- (void)addSubviews{
    self.registerView = [[GSRegisterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
// 注册按钮实现
    [_registerView.registerButton addTarget:self action:@selector(registerButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
// 获取验证码按钮实现
    [_registerView.getSecurityNumButton addTarget:self action:@selector(getSecurityNumButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_registerView];
}

#pragma mark-------------获取验证码--------------
- (void)getSecurityNumButtonAction:(UIButton *)button{
    // 判断号码 正不正确
    // 正确 则 去数据请求
    if ([self isQualified]) {
        // 添加提示框
         UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"正在发送中..." message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alerController animated:YES completion:nil];
        
        UITextField *textField = (UITextField *)[_registerView viewWithTag:100];
        NSDictionary *dic = @{@"request":@{@"codetype":@1,
                                           @"phoneNumber":textField.text,
                                           @"email":@"",
                                           @"username":@""}
                              };
        // 网络请求
[GSNetworkManager requestWithUrlStr:kRegisterGetVerification paraDict:dic method:POST success:^(NSURLResponse *response, NSData *data) {
    if (data) {
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        // 改变弹窗 的标题

        NSString *result = dic[@"result"];
        if (result != nil) {
            alerController.title = result;
        }else{
            alerController.title = dic[@"errorMessage"];
            
        }
        UIAlertAction *makeSureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alerController addAction:makeSureAction];
    }
} failure:^(NSError *error) {
    
}];
    }
}

#pragma mark-----------注册按钮-----------------
- (void)registerButtonAction:(UIButton *)button{
// 获取 密码输入框
    UITextField *passwordTextField = (UITextField *)[_registerView viewWithTag:102];
// 判断 是否 所有的 textField都已输入信息
    for (int i = 0; i < 4; i++) {
        UITextField *textField = (UITextField *)[_registerView viewWithTag:100 + i];
        if (textField.text.length == 0) {
            [textField becomeFirstResponder];
            return;
        }
    }
    // 密码少于6位,不让注册
       if (passwordTextField.text.length < 6) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"密码不能少于6位" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:cancel];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    if ([self isQualified]) {
        // 添加提示框
        UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"正在获取..." message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alerController animated:YES completion:nil];
        // 获取 输入的信息
        UITextField *phoneNumTextField = (UITextField *)[_registerView viewWithTag:100];
         UITextField *userNameTextField = (UITextField *)[_registerView viewWithTag:101];
       UITextField *securityNumTextField = (UITextField *)[_registerView viewWithTag:103];
        // 构建网络请求所需要的 参数字典
        NSDictionary *dic = @{@"request":@{@"phoneNumber":phoneNumTextField.text,
                                           @"userName":userNameTextField.text,
                                           @"email":@"",
                                           @"password":passwordTextField.text,
                                           @"question":@"",
                                           @"answer":@"",
                                           @"phoneVerificationCode":securityNumTextField.text}
                              };        
// 请求
        [GSNetworkManager requestWithUrlStr:kRegister paraDict:dic method:POST success:^(NSURLResponse *response, NSData *data) {
            if (data) {
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                NSString *result = dic[@"result"];
                if (!result) {
                 alerController.title = result;
                }else{
                    alerController.title = dic[@"errorMessage"];
                   
                }
                // 添加 确定按钮
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alerController addAction:cancel];
            }
        } failure:^(NSError *error) {
            
        }];
    }
}
#pragma mark--------------判断号码textField是否规范合格--------
- (BOOL)isQualified{
    // 获取 号码的textField
    UITextField *phoneNumTextField = (UITextField *)[_registerView viewWithTag:100];
    BOOL isQualified = [self valiMobile:phoneNumTextField.text];
    if (isQualified == NO) {
        // 提示框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"手机号码不正确" message:@"请重新输入" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *makeSureAciton = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 按钮添加
        [alertController addAction:makeSureAciton];
        [self presentViewController:alertController animated:YES completion:nil];
        return NO;
    }else{
        return YES;
    }
}
#pragma mark--------------判断号码字符串是否规范---------------
- (BOOL)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}
#pragma mark----------回收键盘-------------------
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark--------------------------------------------
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
